package com.webreport.utils;

import java.io.IOException;
import java.io.StringWriter;

import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.map.DeserializationConfig;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.SerializationConfig;
import org.json.JSONException;
import org.json.JSONObject;

public class JsonUtils {
	private static ObjectMapper mapper;
	private static ObjectMapper inputmapper;
	private static ObjectMapper getMapper(){
		if (mapper ==null){
			java.text.DateFormat dateFormat = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	        mapper = new ObjectMapper();
			mapper.configure(SerializationConfig.Feature.WRAP_ROOT_VALUE, false);
			//mapper.configure(SerializationConfig.Feature.WRITE_NULL_MAP_VALUES, true);
			mapper.configure(SerializationConfig.Feature.WRITE_NULL_PROPERTIES, false);
			mapper.configure(SerializationConfig.Feature.WRITE_DATES_AS_TIMESTAMPS, true);
			mapper.getSerializationConfig().setDateFormat(dateFormat);
		}
		return mapper;
	}
	private static ObjectMapper getInputMapper(){
		if (inputmapper ==null){
			inputmapper = new ObjectMapper();
		}
		return inputmapper;
	}
	public static String toJson(Object value){
		String s = null;
		try {
			s = getMapper().writeValueAsString(value);
		} catch (JsonGenerationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (JsonMappingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return s;
	}
	public static Object fromJson(String s,Class clz) {
		Object o = null;
		try {
			 o  = getInputMapper().readValue(s, clz);
		} catch (Exception e) {
			e.printStackTrace();
		} 
		return o;
	}
}